package com.chengcang.admin.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chengcang.admin.modules.busi.dao.BusiAddressDao;
import com.chengcang.admin.modules.busi.dao.BusiDemandDao;
import com.chengcang.admin.modules.busi.dao.BusiInvoiceHeadDao;
import com.chengcang.admin.modules.busi.dao.BusiOrderDao;
import com.chengcang.admin.modules.busi.entity.BusiAddressEntity;
import com.chengcang.admin.modules.busi.entity.BusiInvoiceHeadEntity;
import com.chengcang.admin.modules.busi.entity.BusiOrderEntity;
import com.chengcang.admin.modules.security.dao.SysUserTokenDao;
import com.chengcang.admin.modules.security.service.SysUserTokenService;
import com.chengcang.admin.modules.sys.dao.*;
import com.chengcang.admin.modules.sys.dto.orderSnapshotDTO.SysOrderTenantSnapshotDTO;
import com.chengcang.admin.modules.sys.entity.*;
import com.chengcang.admin.modules.sys.entity.orderSnapshotEntity.SysOrderTenantSnapshotEntity;
import com.chengcang.admin.modules.sys.service.*;
import com.chengcang.common.enums.DataTypeEnum;
import com.chengcang.common.exception.CustomException;
import com.chengcang.common.exception.ErrorCode;
import com.chengcang.common.redis.RedisUtils;
import com.chengcang.common.service.impl.CrudServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 客户管理
 *
 * @author zhanli
 * @since 1.0.0 2023-01-05
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SysOrderTenantSnapshotServiceImpl extends CrudServiceImpl<SysOrderTenantSnapshotDao, SysOrderTenantSnapshotEntity, SysOrderTenantSnapshotDTO> implements SysOrderTenantSnapshotService {

    private final SysUserTenantDao sysUserTenantDao;
    private final SysUserDao sysUserDao;
    private final BusiInvoiceHeadDao busiInvoiceHeadDao;
    private final BusiAddressDao busiAddressDao;
    private final SysDictDataService sysDictDataService;
    private final BusiOrderDao busiOrderDao;
    private final BusiDemandDao busiDemandDao;
    private final SysRoleDao sysRoleDao;
    private final SysUserTokenDao sysUserTokenDao;
    private final SysTenantBindingsDao sysTenantBindingsDao;

    private final SysTenantMenuService sysTenantMenuService;
    private final SysRoleMenuService sysRoleMenuService;
    private final SysUserTokenService sysUserTokenService;
    private final SysTenantBindingsService sysTenantBindingsService;
    private final RedisUtils redisUtils;


    @Override
    public SysOrderTenantSnapshotDTO getDetail(Long id) {
        SysOrderTenantSnapshotDTO tenantDTO = get(id);
        if (tenantDTO == null) {
            throw new CustomException(ErrorCode.TENANT_EXIST);
        }

        BusiOrderEntity busiOrderEntity = busiOrderDao.selectOne(new LambdaQueryWrapper<BusiOrderEntity>().eq(BusiOrderEntity::getTenantId, id)
                .orderByDesc(BusiOrderEntity::getCreateDate).last("limit 1"));
        if (busiOrderEntity != null) {
            tenantDTO.setLastOrderDate(busiOrderEntity.getCreateDate());
        }

        // 补充账号
        List<SysUserTenantEntity> userTenantEntities = sysUserTenantDao.selectList(new LambdaQueryWrapper<SysUserTenantEntity>()
                .eq(SysUserTenantEntity::getTenantId, tenantDTO.getId())
        );
        if (CollectionUtils.isNotEmpty(userTenantEntities)) {
            LambdaQueryWrapper<SysUserEntity> queryWrapper = new LambdaQueryWrapper<SysUserEntity>()
                    .eq(SysUserEntity::getDefaultUserType, 1)
                    .in(SysUserEntity::getId, userTenantEntities.stream().map(SysUserTenantEntity::getUserId).collect(Collectors.toList()));
            SysUserEntity sysUserEntity = sysUserDao.selectOne(queryWrapper);
            tenantDTO.setRealName(sysUserEntity.getRealName());
            tenantDTO.setMobile(sysUserEntity.getMobile());
            tenantDTO.setGender(sysUserEntity.getGender());
        }
        // 补充抬头
        LambdaQueryWrapper<BusiInvoiceHeadEntity> queryWrapper = new LambdaQueryWrapper<BusiInvoiceHeadEntity>()
                .eq(BusiInvoiceHeadEntity::getTenantId, id)
                .eq(BusiInvoiceHeadEntity::getDefaulted, 0);
        BusiInvoiceHeadEntity invoiceHeadEntity = busiInvoiceHeadDao.selectOne(queryWrapper);

        if (invoiceHeadEntity != null) {
            tenantDTO.setInvoiceHead(invoiceHeadEntity.getInvoiceHead());
            tenantDTO.setInvoiceCode(invoiceHeadEntity.getInvoiceCode());
            tenantDTO.setInvoiceBankName(invoiceHeadEntity.getInvoiceBankName());
            tenantDTO.setInvoiceBankAccount(invoiceHeadEntity.getInvoiceBankAccount());
            tenantDTO.setInvoiceAddress(invoiceHeadEntity.getInvoiceAddress());
            tenantDTO.setInvoiceMobile(invoiceHeadEntity.getInvoiceMobile());
            tenantDTO.setInvoiceEmail(invoiceHeadEntity.getInvoiceEmail());
            tenantDTO.setInvoiceType(invoiceHeadEntity.getInvoiceType());
            tenantDTO.setInvoiceTypeName(sysDictDataService.getValue(DataTypeEnum.INVOICE_TYPE, String.valueOf(tenantDTO.getInvoiceType())));
        }


        tenantDTO.setStatusName(sysDictDataService.getValue(DataTypeEnum.TENANT_STATUS, String.valueOf(tenantDTO.getStatus())));
        tenantDTO.setSourceName(sysDictDataService.getValue(DataTypeEnum.DATA_SOURCE, String.valueOf(tenantDTO.getSource())));
        if (tenantDTO.getTenantType() != null) {
            tenantDTO.setTenantTypeName(sysDictDataService.getValue(DataTypeEnum.TENANT_TYPE, String.valueOf(tenantDTO.getTenantType())));
        }
        // 绑定，性别
        if (StringUtils.isNotBlank(tenantDTO.getBindings())) {
            tenantDTO.setBindingNames(sysDictDataService.getJoiningValue(DataTypeEnum.TENANT_TYPE, tenantDTO.getBindings().split(",")));
        }
        Optional.ofNullable(tenantDTO.getBindingCustomers()).ifPresent(o -> {
            tenantDTO.setBindingCustomerNames(baseDao.selectBatchIds(Arrays.asList(o.split(","))).stream()
                    .map(SysOrderTenantSnapshotEntity::getName).collect(Collectors.joining(",")));

        });
        tenantDTO.setGenderName(sysDictDataService.getJoiningValue(DataTypeEnum.GENDER, String.valueOf(tenantDTO.getGender())));
        //补充收货地址
        LambdaQueryWrapper<BusiAddressEntity> eq = new LambdaQueryWrapper<BusiAddressEntity>().eq(BusiAddressEntity::getDefaulted, 0).eq(BusiAddressEntity::getTenantId, id);
        BusiAddressEntity busiAddressEntity = busiAddressDao.selectOne(eq);
        if (busiAddressEntity != null) {
            tenantDTO.setAddress(busiAddressEntity.getAddress());
            tenantDTO.setProvinceId(busiAddressEntity.getProvinceId());
            tenantDTO.setProvinceName(busiAddressEntity.getProvinceName());
            tenantDTO.setCityId(busiAddressEntity.getCityId());
            tenantDTO.setCityName(busiAddressEntity.getCityName());
            tenantDTO.setAreaId(busiAddressEntity.getAreaId());
            tenantDTO.setAreaName(busiAddressEntity.getAreaName());
            tenantDTO.setConsignee(busiAddressEntity.getConsignee());
            tenantDTO.setAddressMobile(busiAddressEntity.getAddressMobile());
            tenantDTO.setTag(busiAddressEntity.getTag());
        }
        return tenantDTO;
    }

    @Override
    public QueryWrapper<SysOrderTenantSnapshotEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");
        QueryWrapper<SysOrderTenantSnapshotEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        return wrapper;
    }
}
